package com.imageChat.card;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class ServerThread implements Runnable{
	
	List msgList;
	
	ObjectInputStream ois;
	ObjectOutputStream oos;
	Socket socket;
	
	public ServerThread(Socket clientSocket, List msgList) {
		try{

			this.msgList = msgList;
			socket = clientSocket;
			ois = new ObjectInputStream(socket.getInputStream());
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void tellEveryone(String msg){
		
		Iterator it = msgList.iterator();
		
		while(it.hasNext()){
			try{
				oos = (ObjectOutputStream) it.next();
				oos.writeObject(msg);
				oos.flush();
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void run() {
		
		System.out.println(Thread.activeCount()); 

		String msg;
		try{
			while ((msg = (String) ois.readObject()) != null) {
				System.out.println("read" + msg);
				tellEveryone(msg);
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
